package com.ws.shop.action.admin;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.ws.shop.bean.Page;
import com.ws.shop.entity.Accessory;
import com.ws.shop.entity.Auction;
import com.ws.shop.entity.Goods;
import com.ws.shop.entity.Member;
import com.ws.shop.service.AuctionService;
import com.ws.shop.service.GoodsService;
import com.ws.shop.service.MemberService;
import com.ws.shop.util.DateUtil;
import com.ws.shop.util.RequestUtil;

@Controller
@RequestMapping(value="/admin/auction/*")
public class AuctionAction extends BaseAdminAction{
	private static Logger log = Logger.getLogger(AuctionAction.class);
	@Autowired
	private AuctionService auctionService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private MemberService memberService;
	
	@RequestMapping(value="index.jhtml",method=RequestMethod.GET)
	public String index(HttpServletRequest request,Model model){
		String q_goodsname = RequestUtil.getStringParameter(request, "q_goodsname", null);
		int pageno = RequestUtil.getIntParameter(request, Page.PAGE_NO, 1);
		Page page = auctionService.findAuctionListPage(pageno,0,q_goodsname);
		model.addAttribute(Page.PAGE, page);
		model.addAttribute("q_goodsname", q_goodsname);
		model.addAttribute("stateDescs", Auction.STATE_DESCS);
		return "auction_index";
	}
	
	@RequestMapping(value="input.jhtml",method=RequestMethod.GET)
	public String input(HttpServletRequest request,Model model){
		int id = RequestUtil.getIntParameter(request, "id", 0);
		int gid = RequestUtil.getIntParameter(request, "gid", 0);
		if(id == 0){
			Goods goods = goodsService.findGoodsById(gid);
			if(goods == null){
				model.addAttribute(ERROR_MSG, "请选择要添加的竞拍商品");
				return ERROR;
			}
			model.addAttribute("goods", goods);
		}else if(id > 0){
			Auction auction = auctionService.findAuctionById(id);
			if(auction == null){
				model.addAttribute(ERROR_MSG, "请选择要编辑的竞拍商品");
				return ERROR;
			}
			gid = auction.getGid();
			model.addAttribute("auction", auction);
		}else{
			model.addAttribute(ERROR_MSG, "参数错误");
			return ERROR;
		}
		List<Accessory> accessoryList = goodsService.findAccessoryListByGoodsId(gid);
		model.addAttribute("accessoryList", accessoryList);
		model.addAttribute("id", id);
		model.addAttribute("saveImagUrl",AccessoryAction.SAVE_IMAG_URL);
		return "auction_input";
	}
	
	@RequestMapping(value="save.jhtml",method=RequestMethod.POST)
	public String save(HttpServletRequest request,HttpServletResponse response){
		int id = RequestUtil.getIntParameter(request, "id", 0);
		int gid = RequestUtil.getIntParameter(request, "gid", 0);
		String sn = RequestUtil.getStringParameter(request, "sn", null);
		String goodsname = RequestUtil.getStringParameter(request, "goodsname", null);
		int goods_pic = RequestUtil.getIntParameter(request, "goods_pic", 0);
		float costprice = RequestUtil.getFloatParameter(request, "costprice", 0);
		float goodsprice = RequestUtil.getFloatParameter(request, "goodsprice", 0);
		String starttime = RequestUtil.getStringParameter(request, "starttime", null);
		String endtime = RequestUtil.getStringParameter(request, "endtime", null);
		float startprice = RequestUtil.getFloatParameter(request, "startprice", 0);
		float addprice = RequestUtil.getFloatParameter(request, "addprice", 0);
		int addsecond = RequestUtil.getIntParameter(request, "addsecond", 0);
		int usebeat = RequestUtil.getIntParameter(request, "usebeat", 0);
		int recommend = RequestUtil.getIntParameter(request, "recommend", 0);
		int agoid = RequestUtil.getIntParameter(request, "agoid", 0);
		int robots = RequestUtil.getIntParameter(request, "robots", 0);
		int type = RequestUtil.getIntParameter(request, "type", 0);
		int pointc = RequestUtil.getIntParameter(request, "pointc", 0);
		int rebate = RequestUtil.getIntParameter(request, "rebate", 0);
		int delaytype = RequestUtil.getIntParameter(request, "delaytype", 0);
		int boutlimit = RequestUtil.getIntParameter(request, "boutlimit", 0);
		int iskeep = RequestUtil.getIntParameter(request, "iskeep", 0);
		int isdiscount = RequestUtil.getIntParameter(request, "isdiscount", 0);
		int beforebout = RequestUtil.getIntParameter(request, "beforebout", 0);
		int discount = RequestUtil.getIntParameter(request, "discount", 0);
		int isfree = RequestUtil.getIntParameter(request, "isfree", 0);
		int maxaddsecond = RequestUtil.getIntParameter(request, "maxaddsecond", 0);
		if(isfree != 0)
			usebeat = 0;
		float realprice = 0;
		Auction auction = null;
		if(id == 0){
			realprice = startprice;
			auction = new Auction(0,sn,gid,goodsname,goodsprice,goods_pic,
					DateUtil.stringToDate(starttime,DateUtil.YYYY_MM_DD_HH_MM_SS),
					DateUtil.stringToDate(endtime,DateUtil.YYYY_MM_DD_HH_MM_SS),
					null,startprice,addsecond,addprice,usebeat,pointc,costprice,
					recommend,0,realprice,null,0,robots,0,0,
					0,0,agoid,0,delaytype,type,rebate,boutlimit,iskeep,beforebout,
					discount,isdiscount,isfree,maxaddsecond,0);
		}else{
			auction = auctionService.findAuctionById(id);
			realprice = auction.getRealprice() - auction.getStartprice() + startprice;
			auction = new Auction(id,sn,gid,goodsname,goodsprice,goods_pic,
					DateUtil.stringToDate(starttime,DateUtil.YYYY_MM_DD_HH_MM_SS),
					DateUtil.stringToDate(endtime,DateUtil.YYYY_MM_DD_HH_MM_SS),
					null,startprice,addsecond,addprice,usebeat,pointc,costprice,
					recommend,0,realprice,null,0,robots,0,0,
					0,0,agoid,0,delaytype,type,rebate,boutlimit,iskeep,beforebout,
					discount,isdiscount,isfree,maxaddsecond,0);
		}
		try{
			auctionService.saveOrUpdate(auction);
			return this.ajaxJsonSuccessMessage(response, "操作成功");
		}catch(Exception e){
			log.error("操作失败："+auction,e);
			return this.ajaxJsonErrorMessage(response, "操作失败");
		}
	}
	
	@RequestMapping(value="showrobots.jhtml",method=RequestMethod.GET)
	public String showrobots(HttpServletRequest request,Model model){
		int aid = RequestUtil.getIntParameter(request, "aid", 0);
		int pageno = RequestUtil.getIntParameter(request, Page.PAGE_NO, 1);
		Auction auction = auctionService.findAuctionById(aid);
		Page page = auctionService.findSelectRobotsByAidPage(pageno, 10, aid);
		model.addAttribute("auction", auction);
		model.addAttribute(Page.PAGE, page);
		model.addAttribute("aid", aid);
		model.addAttribute("stateDescs", Member.STATE_DESCS);
		return "auction_show_robots";
	}
	
	@RequestMapping(value="addauctionrobot.jhtml",method=RequestMethod.POST)
	public String addauctionrobot(HttpServletRequest request,HttpServletResponse response){
		int aid = RequestUtil.getIntParameter(request, "aid", 0);
		int uid = RequestUtil.getIntParameter(request, "uid", 0);
		if(aid <=0 || uid <=0){
			return this.ajaxJsonErrorMessage(response, "参数有误");
		}
		try{
			auctionService.addauctionrobot(aid,uid);
			return this.ajaxJsonSuccessMessage(response, "添加成功");
		}catch(Exception e){
			log.error("添加机器人失败 aid="+aid+";uid="+uid,e);
			return this.ajaxJsonErrorMessage(response, "系统繁忙，请稍后再试");
		}
	}
	
	@RequestMapping(value="delauctionrobot.jhtml",method=RequestMethod.POST)
	public String delauctionrobot(HttpServletRequest request,HttpServletResponse response){
		int rid = RequestUtil.getIntParameter(request, "rid", 0);
		if(rid <= 0){
			return this.ajaxJsonErrorMessage(response, "参数有误");
		}
		try{
			auctionService.delauctionrobot(rid);
			return this.ajaxJsonSuccessMessage(response, "删除成功");
		}catch(Exception e){
			log.error("删除机器人失败 rid="+rid,e);
			return this.ajaxJsonErrorMessage(response, "系统繁忙，请稍后再试");
		}
	}
	
//	public String saveRobots(HttpServletRequest request,HttpServletResponse response){
//		String idsStr = RequestUtil.getStringParameter(request, "ids", null);
//		int ids[] = StringUtil.string2IntArray(idsStr, ";");
//		int aid = RequestUtil.getIntParameter(request, "aid", 0);
//		int min = RequestUtil.getIntParameter(request, "min", 0);
//		int max = RequestUtil.getIntParameter(request, "max", 0);
//		float target = RequestUtil.getFloatParameter(request, "target", 0);
//		if(ids != null && ids.length >= 3){
//			
//		}else{
//			
//		}
//	}
	
//	public function saveRobots(){
//		$data = Init_GP(array('ids','aid','min','max','target'));
//		$auction = D('Auction');
//		$count = count($data['ids']);
//		if($count >=3 ){
//			$auctiondata = array(
//				'id'=>GetNum($data['aid']),
//				'min'=>GetNum($data['min']),
//				'max'=>GetNum($data['max']),
//				'target'=>GetNum($data['target']),
//				'robots'=>1,
//			);
//			
//			$auction->save($auctiondata);
//			$aid = GetNum($data['aid']);
//			if (!empty($data)) {
//				$robot = M('Robot');
//				$map['aid'] = array('eq',$aid);
//				$robot->where($map)->delete();
//				$robotdata['aid'] = $aid;
//				foreach ($data['ids'] as $val){
//					$robotdata['uid'] = $val;
//					$robot->add($robotdata);
//					unset($robotdata['uid']);				
//				}
//			}
//		}else{
//			$auctiondata = array(
//				'id'=>GetNum($data['aid']),
//				'robots'=>0,
//			);
//			$auction->save($auctiondata);
//		}
//	}
	
	public String auction_end_show(HttpServletRequest request,Model model){
		int id = RequestUtil.getIntParameter(request, "id", 0);
		model.addAttribute("id", id);
		return "auction_end_show";
	}

	public String auction_end_save(HttpServletRequest request,HttpServletResponse response){
		int id = RequestUtil.getIntParameter(request, "id", 0);
		int uid = RequestUtil.getIntParameter(request, "uid", 0);
		Member user = memberService.findMemberById(uid);
		if(user == null)
			return this.ajaxJsonErrorMessage(response, "指定用户不存在");
		Auction auction = new Auction();
		auction.setId(id);
		auction.setUid(uid);
		auction.setAuctionuname(user.getName());
		auction.setEndtime(new Date());
		auction.setState(2);
		try{
			auctionService.saveEnd(auction);
			return this.ajaxJsonSuccessMessage(response, "更新成功");
		}catch(Exception e){
			log.error("更新失败",e);
			return this.ajaxJsonErrorMessage(response, "系统异常，请稍后再试");
		}
	}
	
}
